package com.gzc.pm.logic
{
	import cn.skyclass.net.BaseLoader;
	
	import com.gzc.pm.bean.CPLAxleBean;
	import com.gzc.pm.bean.CPLLineBean;
	import com.gzc.pm.bean.CPLRouteBean;
	import com.gzc.pm.dao.CplAxleDao;
	import com.gzc.pm.dao.CplLineDao;
	import com.gzc.pm.dao.CplRouteDao;
	import com.gzc.pm.util.GlobalData;
	
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	
	[Bindable]
	public class CplAxleLoader extends BaseLoader
	{
		public function CplAxleLoader()
		{
			
		}
		
		public var axles:ArrayCollection;
		public var axleDict:Dictionary;
		public var lines:ArrayCollection;
		public var routes:ArrayCollection;
		
		private var axleIds:String; 
		
		override protected function doLoad():void{
			var dao:CplAxleDao = new CplAxleDao();
			dao.getAll(onAxleLoaded);
		}
		
		private function onAxleLoaded(e:ResultEvent):void{
			axles = e.result as ArrayCollection;
			
			axleDict = new Dictionary();
			axleIds = "";
			for each(var axle:CPLAxleBean in axles){
				axleIds += axle.id + ",";
				axle.lines = new ArrayCollection();
				axle.routes = new ArrayCollection();
				axleDict[axle.id] = axle;
			}
			axleIds += "-1";
			
			var cplLineDao:CplLineDao = new CplLineDao();
			cplLineDao.getByAxleIds(axleIds, onLineLoaded);
		}
		
		private function onLineLoaded(e:ResultEvent):void{
			lines = e.result as ArrayCollection;
			
			var cplRouteDao:CplRouteDao = new CplRouteDao();
			cplRouteDao.getByAxleIds(axleIds, onRouteLoaded);
		}
		
		private function onRouteLoaded(e:ResultEvent):void{
			routes = e.result as ArrayCollection;
			dealWithData();
			
			GlobalData.getInstance().axles = axles;
			dispatchLoadedEvent();
		}
		
		private function dealWithData():void{
			for each(var line:CPLLineBean in lines){
				var axle:CPLAxleBean = axleDict[line.axleId];
				if(axle){
					axle.lines.addItem(line);
				}
			}
			
			var rootRouteArray:ArrayCollection = new ArrayCollection();
			//拼装工艺路线树形结构
			for each(var route:CPLRouteBean in routes){
				if(route.parentId == 0){//根路线下，第一级工艺路线
					route.parent = GlobalData.getInstance().treeRoot;
					rootRouteArray.addItem(route);
				}
				for each(var route1:CPLRouteBean in routes){
					if(route1.parentId == route.id){
						if(!route.children) route.children = new ArrayCollection();
						route1.parent = route;
						route.children.addItem(route1);
					}
				}
			}
			
			for each(var route:CPLRouteBean in rootRouteArray){
				var axle:CPLAxleBean = axleDict[route.axleId];
				if(axle){
					axle.routes.addItem(route);
				}
			}
		}
		
	}
}